package com.jzo2o.orders.manager.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

//取消订单上下文环境
//1. 维护所有的取消订单的策略对象 Map<String,OrderCancelStrategy>
//2. 提供访方法 根据传入key选择对应策略的对象
@Component
public class OrderCancelStrategyManager {
    private Map<String, OrderCancelStrategy> map = new HashMap<>();

    @Autowired
    private OrdersMapper ordersMapper;

    @PostConstruct
    public void init() {
        //获取所有策略对象,放入map中
        //key: 对象在容器中的id
        map = SpringUtil.getBeansOfType(OrderCancelStrategy.class);
    }


    public void cancel(OrderCancelDTO orderCancelDTO) {
        //1. 根据订单id查询订单信息
        Orders orders = ordersMapper.selectById(orderCancelDTO.getId());
        if (ObjectUtils.isNull(orders)) {
            throw new ForbiddenOperationException("订单不存在");
        }
        BeanUtil.copyProperties(orders, orderCancelDTO);
        orderCancelDTO.setCurrentUserId(orders.getUserId());

        //2. 组装key 根据key从容器中获取出要执行的策略对象
        String key = orderCancelDTO.getCurrentUserType() + ":" + OrderStatusEnum.codeOf(orders.getOrdersStatus()).toString();
        OrderCancelStrategy orderCancelStrategy = map.get(key);
        if (ObjectUtils.isNull(orderCancelStrategy)) {
            throw new ForbiddenOperationException("当前用户的本次操作暂不支持");
        }

        //3. 调用策略类的方法
        orderCancelStrategy.cancel(orderCancelDTO);
    }
}